package day240904;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/login")
public class MyFirstHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.getWriter().write("MyHttpServlet.doGet: username=" + username + ", password=" + password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        // 前端可以先用 js 提前验证用户名和密码是否符合规范，比如：用户/密码的长度 ...
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + "," + password);

        boolean isOk = false;
        Connection connection = MyDBUtil.getConnection();
        try {
            // 重要提醒：以后保存到我们数据库的密码都应该是加密之后的。
            // 作为开发工程师，你可以知道很多内部的对象，但是我们不要知道太多。知道越多，活不过两集
            PreparedStatement ps = connection.prepareStatement("select `username`, `password` from users where `username`=?");
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                String password1 = rs.getString("password");
                if (password.equals(password1)) {
                    isOk = true;
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (isOk) {
            // 登录成功
            writer.write("登录成功！用户名：" + username);
            resp.sendRedirect("http://120.26.106.52/");
        } else {
            // 登录失败
            writer.write("登录失败！");
            writer.write("<br>");
            writer.write("<a href='/am_web2_war/day240904/login.html'>返回登录页面</a>");
        }
    }
}